// background.ts

// TEMU 相关
// 存储店铺信息
let shopInfo = null;
let tempAntiContent = "";
// 添加一个标志变量，表示是否已经请求过
let userInfoRequested = false;

interface HtmlResponse {
  code: number;
  data: string[];
}

interface Html {
  getHtmlNew(
    url: string,
    options: { try_times: number },
    callback: (response: string) => void
  ): void;
  postHtmlNew(
    url: string,
    options: { data: { url: string }; httpType: string },
    callback: (response: HtmlResponse) => void
  ): void;
}

interface URLManager {
  url: {
    postAmazon: () => string;
  };
}

// Define Html and s objects or fetch them from somewhere
const Html: Html = {
  getHtmlNew: (url, options, callback) => {
    // Example implementation using fetch

    fetch(url)
      .then((response) => response.text())
      .then((text) => callback(text))
      .catch((error) => console.error("Error fetching HTML:", error));
  },
  postHtmlNew: (url, options, callback) => {
    // Example implementation using fetch
    fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
      body: new URLSearchParams(options.data as any).toString(),
    })
      .then((response) => response.json())
      .then((data) => callback(data))
      .catch((error) => console.error("Error posting HTML:", error));
  },
};

function capitalizeFirstLetter(str: any) {
  if (typeof str !== "string" || str.length === 0) {
    return str; // 如果不是字符串或空字符串，直接返回
  }
  return str.charAt(0).toUpperCase() + str.slice(1);
}

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.type === "callApi") {
    const queryParams = new URLSearchParams(request.data).toString();
    fetch(
      `https://java.baoyierp.com/api/goods-launch-${
        request.platform
      }/commonData/selectList/launchCollectProductSkuRecord${capitalizeFirstLetter(
        request.platform
      )}?${queryParams}`,
      {
        method: "GET",
        headers: {
          "Content-Type": "application/json",
          Authorization: "Bearer " + request.token,
        },
      }
    )
      .then((res) => res.json())
      .then((data) => sendResponse(data))
      .catch((err) => sendResponse({ error: err.message }));
    return true; // 保持消息通道开放
  } else if (request.type === "getAntiContent") {
    sendResponse(tempAntiContent);
  } else if (request.type === "updateBatchBysSkuNoGenerate") {
    fetch(
      `https://java.baoyierp.com/api/goods-launch-${
        request.platform
      }/user/LaunchOnlineProductSku${capitalizeFirstLetter(
        request.platform
      )}/updateBatchBysSkuNoGenerate`,
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: "Bearer " + request.token,
        },
        body: JSON.stringify(request.data),
      }
    )
      .then((res) => res.json())
      .then((data) => sendResponse(data))
      .catch((err) => sendResponse({ error: err.message }));
    return true; // 保持消息通道开放
  }
});

chrome.webRequest.onBeforeSendHeaders.addListener(
  function (details) {
    if (userInfoRequested) {
      return;
    }
    if (
      details.url.includes("/bg/quiet/api/mms/userInfo") ||
      details.url.includes("/api/seller/auth/userInfo")
    ) {
      console.log("onBeforeSendHeaders捕获到userInfo请求:", details.url);
      if (details.requestHeaders) {
        // 存储请求头信息供后续使用
        const antiContentHeader = details.requestHeaders.find(
          (h) => h.name.toLowerCase() === "anti-content"
        );
        if (antiContentHeader) {
          console.log("捕获到Anti-Content:", antiContentHeader.value);
          // 临时存储anti-content值
          tempAntiContent = antiContentHeader.value || ""; // 修改这里
          // 标记为已请求
          userInfoRequested = true;
        }
      }
    }
    return { requestHeaders: details.requestHeaders };
  },
  { urls: ["*://*.kuajingmaihuo.com/*", "*://*.temu.com/*"] },
  ["requestHeaders", "extraHeaders"]
);

//
